/*
 * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package com.umeox.watch.moto.gallery.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.gallery.R;
import com.umeox.watch.moto.gallery.db.AppDataBase;
import com.umeox.watch.moto.gallery.db.model.AlbumInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/*
 * Handles basic helper functions used throughout the app.
 */
public class Util {




    /**
     * Converts number of bytes into proper scale.
     *
     * @param bytes number of bytes to be converted.
     * @return A string that represents the bytes in a proper scale.
     */
    public static String getBytesString(long bytes) {
        String[] quantifiers = new String[] {
                "KB", "MB", "GB", "TB"
        };
        double speedNum = bytes;
        for (int i = 0;; i++) {
            if (i >= quantifiers.length) {
                return "";
            }
            speedNum /= 1024;
            if (speedNum < 512) {
                return String.format("%.2f", speedNum) + " " + quantifiers[i];
            }
        }
    }

    /**
     * Copies the data from the passed in Uri, to a new file for use with the
     * Transfer Service
     * 
     * @param context
     * @param uri
     * @return
     * @throws IOException
     */
    public static File copyContentUriToFile(Context context, Uri uri) throws IOException {
        InputStream is = context.getContentResolver().openInputStream(uri);
        File copiedData = new File(context.getDir("SampleImagesDir", Context.MODE_PRIVATE), UUID
                .randomUUID().toString());
        copiedData.createNewFile();

        FileOutputStream fos = new FileOutputStream(copiedData);
        byte[] buf = new byte[2046];
        int read = -1;
        while ((read = is.read(buf)) != -1) {
            fos.write(buf, 0, read);
        }

        fos.flush();
        fos.close();

        return copiedData;
    }



    public static String getDateToString(long milSecond,String pattern) {
        Date date = new Date(milSecond);
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
        return format.format(date);
    }

    /**
     * 设置部分文字字体样式,颜色
     * @param context
     * @param photoCounts 照边数量
     * @param resId 文本资源id,包含占位符
     * @return
     */
    public static SpannableStringBuilder setSpanText(Context context, int photoCounts, int resId) {

        int pixelSize = 18;
        String uploading_photos = String.format(context.getString(resId), photoCounts);
        int index = uploading_photos.indexOf(String.valueOf(photoCounts));
        ColorStateList redColors = ColorStateList.valueOf(context.getResources().getColor(R.color.black));
        TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan("sans-serif-condensed", 0, pixelSize, redColors, null);
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(uploading_photos);
        spanBuilder.setSpan(textAppearanceSpan, index, uploading_photos.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        return spanBuilder;

    }

    public static void deleteImage(Context context,String imgPath) {
        ContentResolver resolver = context.getApplicationContext().getContentResolver();
        Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?",
                new String[]{imgPath}, null);
        boolean result;
        if (cursor.moveToFirst()) {
            long id = cursor.getLong(0);
            Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Uri uri = ContentUris.withAppendedId(contentUri, id);
            int count = context.getApplicationContext().getContentResolver().delete(uri, null, null);
            result = count == 1;
        } else {
            File file = new File(imgPath);
            result = file.delete();
        }
        cursor.close();
        Logger.i("TAG", "result:" + result);

        if (result) {
            //删除自定义数据库中对应的数据
            AlbumInfo albumInfo = AppDataBase.getInstance().albumInfoDao().queryByImagePath(imgPath);
            if(albumInfo != null){
                int result1  =  AppDataBase.getInstance().albumInfoDao().delete(albumInfo);
                Logger.i("TAG", "result1:" + result1);
            }
        }
    }
}
